<template>
  <div>
    <el-card class="margin-top">
      <div slot="header" class="clearfix">
        <span class="title-icon margin-right-sm">装箱单</span>
        <el-button
          class="margin-left"
          size="mini"
          type="success"
          @click="reset"
        >
          重置装箱单
        </el-button>

        <el-button
          class="margin-left"
          size="mini"
          type="success"
          @click="checkFbaNoNotInSub"
        >
          校验FBA箱号
        </el-button>
      </div>

      <template v-if="showBoxDetail">
        <div
          v-for="(item, index) in packingList"
          :key="index"
          class="margin-top"
        >
          <el-row :gutter="20" type="flex" class="align-center">
            <el-col :span="5" class="flex align-center justify-start">
              <!--             : -->
              <i
                style="font-size:26px"
                class="{
                  'el-icon-arrow-down': item.show,
                  'el-icon-arrow-up': !item.show
                }"
                @click="toggleTable(item)"
              />

              <span v-if="item.shipmentId" class="margin-left">
                ShipmentID:{{ item.shipmentId || "" }}
              </span>
            </el-col>
            <el-col :span="5">
              <div class="flex align-center justify-start">
                <span class="head-title">箱号规则：</span>
                <el-select
                  v-model="item.rule"
                  placeholder="请选择"
                  size="mini"
                  @change="
                    val => {
                      changeRule(val, item);
                    }
                  "
                >
                  <el-option
                    v-for="(optionItem, optionIndex) in rulesNo"
                    :key="optionIndex"
                    :label="optionItem"
                    :value="optionItem"
                  />
                </el-select>
              </div>
            </el-col>
            <el-col :span="5">
              <div class="flex align-center justify-start">
                <span class="head-title">起始箱号：</span>
                <el-input
                  v-model="item.startBoxNo"
                  class="flex-treble"
                  type="number"
                  size="mini"
                  placeholder="请填写起始箱号"
                  maxlength="4"
                  max="9999"
                  min="1"
                  @input="
                    item.startBoxNo.length > 4
                      ? (item.startBoxNo = item.startBoxNo.slice(0, 4))
                      : item.startBoxNo
                  "
                />
              </div>
            </el-col>
            <el-col :span="5">
              <div class="flex align-center justify-center">
                <span class="head-title">结束箱号：</span>
                <el-input
                  v-model="item.endBoxNo"
                  class="flex-treble"
                  type="number"
                  size="mini"
                  maxlength="4"
                  max="9999"
                  min="0"
                  placeholder="请填写结束箱号"
                  @input="
                    item.startBoxNo.length > 4
                      ? (item.startBoxNo = item.startBoxNo.slice(0, 4))
                      : item.startBoxNo
                  "
                />
              </div>
            </el-col>
            <el-col :span="4">
              <el-button
                type="primary"
                size="mini"
                @click.native="selectSKU(item, index)"
              >
                选择SKU
              </el-button>
              <el-button
                type="primary"
                size="mini"
                @click.native="delSelectSKU(index)"
              >
                批量删除
              </el-button>
            </el-col>
          </el-row>
          <!-- :span-method="objectSpanMethod" -->
          <el-collapse-transition>
            <el-table
              v-show="item.show"
              ref="multipleTable"
              :header-cell-style="{ background: '#f5f9fc' }"
              size="mini"
              border
              :data="item.tableData"
              :span-method="objectSpanMethod"
              style="width: 100%;"
              class="margin-top "
              tooltip-effect="light"
              @selection-change="handleSelectionChange($event, index)"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column
                label="箱号"
                align="center"
                prop="cartonNo"
                width="200"
              />
              <el-table-column
                prop="grossWeight"
                label="单箱毛重(kg)"
                align="center"
              />
              <el-table-column prop="LWH" label="长×宽×高(cm)" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.length }}</span>
                  <span v-if="scope.row.length">X</span>
                  <span>{{ scope.row.width }}</span>
                  <span v-if="scope.row.width">X</span>
                  <span>{{ scope.row.height }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="skuName"
                label="SKU"
                align="center"
                min-width="400"
                show-overflow-tooltip
              />
              <el-table-column
                prop="declareNameCn"
                label="中文品名"
                align="center"
                min-width="260"
                show-overflow-tooltip
              />
              <el-table-column
                prop="skuNum"
                label="个数"
                align="center"
                min-width="50"
              />
              <el-table-column label="" width="50" align="center">
                <template slot-scope="scope">
                  <i
                    class="el-icon-delete padding-lr-sm pointer"
                    @click="handleDelete(index, scope.$index, scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="编辑" width="60" align="center">
                <template slot-scope="scope">
                  <i
                    class="el-icon-edit padding-lr-sm pointer"
                    @click="handleEdit(index, scope.$index, scope.row)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-transition>
        </div>
      </template>
    </el-card>

    <!--  -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showSelectDialog"
      :close="hideSelectDialog"
      width="60%"
    >
      <div v-if="packingList && packingList[showIndex]" class="dialog-main">
        <p class="text-center">
          {{ dialogHead }}
        </p>

        <el-table
          :ref="`selectTable${showIndex}`"
          :data="selectTable"
          max-height="500"
          tooltip-effect="light"
        >
          <el-table-column type="index" label="序号" width="60" />

          <el-table-column property="skuName" label="SKU" width="300" />
          <el-table-column
            property="declareNameCn"
            label="中文品名"
            show-overflow-tooltip
          />
          <el-table-column property="skuNum" label="总个数" />
          <el-table-column label="剩余个数">
            <template slot-scope="scope">
              <!-- {{ remainingNum(scope.row, showIndex) }} -->
              {{ updateRemainingNum(scope, showIndex, packingList[showIndex]) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="dialogTitle === '选择SKU' ? '装入每箱数量' : '装入该箱数量'"
          >
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.inputNum"
                type="number"
                min="0"
                placeholder="请填写数量"
                @input="remainingNum(scope, showIndex, packingList[showIndex])"
              />
            </template>
          </el-table-column>
        </el-table>
        <el-form class="margin-top" :model="dialogInfo" :rules="dialogRule">
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="110px" prop="grossWeight">
                <div slot="label">单箱毛重(KG):</div>

                <el-input
                  v-model.trim="dialogInfo.grossWeight"
                  clearable
                  :disabled="statusEnable"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16" class="flex ">
              <div
                class="flex-sub form-input-length text-right padding-right-sm"
              >
                <span>单箱长X宽X高(cm):</span>
              </div>

              <el-row :gutter="10" class="flex-twice">
                <el-col :span="7">
                  <el-form-item prop="length" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.length"
                      placeholder="长"
                      :disabled="statusEnable"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="form-input-length">X</el-col>
                <el-col :span="7">
                  <el-form-item prop="width" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.width"
                      placeholder="宽"
                      :disabled="statusEnable"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="form-input-length">X</el-col>
                <el-col :span="7">
                  <el-form-item prop="height" label-width="0">
                    <el-input
                      v-model.trim="dialogInfo.height"
                      placeholder="高"
                      :disabled="statusEnable"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <span v-if="statusEnable" style="color:red;margin-left:50px;">
                运单出库后 箱单重量、长、宽、高不允许修改</span
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideSelectDialog">取 消</el-button>
        <el-button
          v-if="dialogTitle === '选择SKU'"
          type="primary"
          @click="enterSelectSku"
        >
          确 定
        </el-button>
        <el-button v-else type="primary" @click="editSelectSku">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { clone } from "@/utils/clone";
import { m } from "@/store/yg/common/local";
import { ajax } from "@/store/yg/common/utils";
import { getSpanArr, changeCartonNo } from "@/utils/invoice-table";

export default {
  name: "PackingList",
  filters: {
    sliceName(name) {
      if (!name) return "";
      return name.slice(2);
    }
  },
  props: {
    packingList: {
      type: Array,
      default: []
    },
    statusEnable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showBoxDetail: true,
      dialogTitle: "选择SKU",
      dialogHead: "选择SKU",
      showRowIndex: 0,
      // packingList: this.packingInfo,
      showSelectDialog: false,
      multipleSelection: [],
      rulesNo: ["U001", "U0001", "U00001", "U000001"],
      spanArr: [],
      tableData: [],
      showIndex: "",
      selectTableData: {},
      dialogInfo: {
        length: "",
        width: "",
        height: "",
        grossWeight: ""
      },
      selectTable: [],
      dialogRule: {
        length: [
          { required: false, message: "请填写正整数", trigger: "blur" },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: "须为数字,可留3位小数"
          }
        ],
        width: [
          { required: false, message: "请填写正整数", trigger: "blur" },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: "须为数字,可留3位小数"
          }
        ],
        height: [
          { required: false, message: "请填写正整数", trigger: "blur" },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: "须为数字,可留3位小数"
          }
        ],
        grossWeight: [
          { required: false, message: "请填写正整数", trigger: "blur" },
          {
            pattern: /^[+]?\d*\.?\d{0,3}$/,
            message: "须为数字,可留3位小数"
          }
        ]
      }
    };
  },
  computed: {
    // ...mapGetters(['invoiceInfo', 'channelFormLeft', 'packingInfo'])
    getInfo() {
      console.log("getInfo", this.packingList);
      return this.packingList;
    },
    updateRemainingNum() {
      return function(scope, index, data) {
        let num = 1;
        if (this.dialogTitle === "选择SKU") {
          const p = this.packingList[index];
          num =
            1 -
            parseInt(p.startBoxNo) +
            parseInt(p.endBoxNo ? p.endBoxNo : p.startBoxNo);
          return (
            scope.row.skuNum - scope.row.packingNum - scope.row.inputNum * num
          );
        } else {
          return scope.row.skuNum - scope.row.packingNum - scope.row.inputNum;
        }
      };
    }
  },

  watch: {
    "$parent.packingInfo": {
      handler(newVal, oldVal) {
        // console.log('newVal :>> ', newVal)
        this.packingList = newVal;
      }
    },
    packingList: {
      handler(nVal, oVal) {
        if (!nVal) return;

        console.log("变化");

        this.$parent.packingInfo = nVal;
      }
    }
  },
  mounted() {},
  methods: {
    checkFbaNoNotInSub() {
      var param = {};
      param["id"] = this.$route.query.waybillId;
      ajax("checkFbaNoNotInSub", param).then(
        res => {
          console.log(res);
          if (res.code != 200) {
            this.$message.error("系统错误");
          } else {
            if (res.data) {
              // $.each(data.fbaNos,function(i,n){
              // 	$('tr[name="'+n+'"]').find('td:eq(0)').css('color','#FF7575');
              // })
              this.$message.error(res.data);
            } else if (res.data2) {
              this.$message.error(res.data2);
            } else {
              this.$message.success("所有箱号都已匹配上!");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    reset() {
      console.log("12121 :>> ", 12121);
      this.$emit("resetPacking");
    },

    async delSelectSKU(index) {
      console.log(
        "this.packingList[index] :>> ",
        this.packingList[index].multipleSelection
      );
      const obj = clone(this.packingList[index]);
      if (!obj.multipleSelection || obj.multipleSelection.length === 0) {
        this.$message.error("请选择要删除的数据！");
        return;
      }

      const table = clone(obj.tableData);
      console.log("table :>> ", table);

      for (const j of obj.multipleSelection) {
        for (let i = table.length - 1; i >= 0; i--) {
          if (table[i].cartonNo === j.cartonNo) {
            table.splice(i, 1);
          }
        }
      }

      obj.tableData = table;
      for (const i of obj.filterData) {
        for (const j of obj.multipleSelection) {
          if (i.skuName === j.skuName) {
            i.packingNum -= j.skuNum;
          }
        }
      }

      if (
        this.packingList[index].tableData.length > 1 &&
        obj.multipleSelection.length !==
          this.packingList[index].tableData.length
      ) {
        this.$set(this.packingList, index, await getSpanArr(obj));
      } else {
        this.$set(this.packingList, index, obj);
      }
    },

    resetPacking() {},
    // 弹出框标题
    dialogHeadFn() {
      // if (!this.showIndex) return
      let head = "";
      const p = this.packingList[this.showIndex];
      if (this.dialogTitle === "选择SKU") {
        const cartonNo =
          p.rule.slice(0, p.rule.length - p.startBoxNo.toString().length) +
          p.startBoxNo;

        head = `箱号：${cartonNo} - ${p.endBoxNo ? p.endBoxNo : p.startBoxNo} 共
          ${1 -
            parseInt(p.startBoxNo) +
            parseInt(p.endBoxNo ? p.endBoxNo : p.startBoxNo)}箱`;
      } else {
        const num = p.tableData[this.showRowIndex].cartonNo.slice(2);

        head = `箱号 ${num}`;
      }

      this.dialogHead = head;
    },
    // 判断剩余数量是否足够
    remainingNum(scope, index, data) {
      let num = 1;
      const p = this.packingList[index];
      if (this.dialogTitle === "选择SKU") {
        num =
          parseInt(scope.row.skuNum) -
          parseInt(scope.row.packingNum) -
          parseInt(scope.row.inputNum) *
            (1 -
              parseInt(p.startBoxNo) +
              parseInt(p.endBoxNo ? p.endBoxNo : p.startBoxNo));
        if (num < 0) {
          this.$message.error("SKU个数超过剩余个数");
          scope.row.inputNum = "0";
          return parseInt(scope.row.skuNum);
        } else {
          return parseInt(num);
        }
      } else {
        num =
          parseInt(scope.row.skuNum) -
          parseInt(scope.row.packingNum) -
          parseInt(scope.row.inputNum);
        console.log("num :>> ", num);
        if (num < 0) {
          this.$message.error("SKU个数超过剩余个数");
          scope.row.inputNum = "0";
          return parseInt(scope.row.skuNum);
        } else {
          return parseInt(num);
        }
      }
    },
    handleSelectionChange(val, index) {
      // this.multipleSelection = val;
      const arr = [];
      for (const i of val) {
        arr.push(i.cartonNo);
      }
      this.$delete(this.packingList[index], "multipleSelection");
      this.$set(this.packingList[index], "multipleSelection", val);
    },
    // 计算表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 0 ||
        columnIndex === 1 ||
        columnIndex === 2 ||
        columnIndex === 3 ||
        columnIndex === 8
      ) {
        // console.log('%crow: ', 'color: #fff; background: #67C23A;', row)
        // console.log(
        //   '%cthis.packingList: ',
        //   'color: #fff; background: #67C23A;',
        //   this.packingList
        // )
        if (!(row.shipmentId === "" || row.shipmentId)) {
          // console.log('表格合并缺乏shipmentId :>> ')
        }
        // 关键字段  shipmentId 一定要存在
        const target = this.packingList.find(
          x => x.shipmentId === row.shipmentId
        );
        // console.log('target :>> ', target)
        const row_span =
          target && (target.spanArr[rowIndex] || target.spanArr[rowIndex] === 0)
            ? target.spanArr[rowIndex]
            : 1;
        return {
          rowspan: row_span,
          colspan: 1
        };
      }
    },
    handleEdit(index, rowIndex, row) {
      // console.log(index, rowIndex, row)
      this.showIndex = index;
      this.showRowIndex = rowIndex;
      this.dialogTitle = "编辑箱单SKU个数";
      this.dialogHeadFn();
      const arr = [];
      const nameArr = [];
      console.log(this.packingList);
      const targetData = this.packingList[index].tableData[rowIndex];
      // 回显 长宽高 毛重
      this.dialogInfo.length = targetData.length;
      this.dialogInfo.width = targetData.width;
      this.dialogInfo.height = targetData.height;
      this.dialogInfo.grossWeight = targetData.grossWeight;
      //
      for (const i of this.packingList[index].tableData) {
        if (i.cartonNo === targetData.cartonNo) {
          arr.push(i);
          nameArr.push(i.skuName);
        }
      }
      //  当前选中的表格数据
      this.selectTableData = {
        data: arr,
        nameArr: nameArr
      };
      this.selectTable = clone(this.packingList[index].filterData);
      // 初始化 输入数量
      this.selectTable.forEach(i => {
        i.inputNum = "0";
      });
      //
      for (const j of this.selectTableData.data) {
        for (const i of this.selectTable) {
          if (i.skuName === j.skuName) {
            const num = clone(i.packingNum);
            // if (num) {
            i.inputNum = j.skuNum;
            i.packingNum = num - j.skuNum;
            // }
          }
        }
      }

      this.showSelectDialog = true;
    },
    // 删除数据
    async handleDelete(index, rowIndex, row) {
      this.$confirm("确认删除改行么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.delRow(index, rowIndex, row);
        })
        .catch(() => {});
    },
    //
    async delRow(index, rowIndex, row) {
      this.showIndex = index;
      this.showRowIndex = rowIndex;
      const obj = Object.assign({}, this.packingList[index]);
      const arr = obj.tableData.filter((val, j) => {
        if (j !== rowIndex) {
          return val;
        }
      });
      obj.tableData = arr;
      for (const i of obj.filterData) {
        if (i.skuName === row.skuName) {
          i.packingNum -= row.skuNum;
        }
      }
      if (this.packingList[index].length > 1) {
        this.$set(this.packingList, this.showIndex, await getSpanArr(obj));
      } else {
        this.$set(this.packingList, this.showIndex, obj);
      }
    },
    toggleTable(item) {
      console.log(item);
      const flag = !item.show;
      this.$delete(item, "show");
      this.$set(item, "show", flag);
    },
    selectSKU(item, index) {
      this.dialogTitle = "选择SKU";
      // 清除上一次输入的 长宽高 毛重
      item.length = "";
      item.width = "";
      item.height = "";
      item.grossWeight = "";

      // 箱号.length == 箱数
      const cartonNoList = [];
      for (const i of this.packingList[index].tableData) {
        if (!cartonNoList.includes(i.cartonNo)) {
          cartonNoList.push(i.cartonNo);
        }
      }

      if (
        item.rule === "U001" &&
        parseInt(item.endBoxNo) -
          parseInt(item.startBoxNo) +
          cartonNoList.length >
          999
      ) {
        this.$notify.error({
          title: "箱号规则U001 ",
          message: "总箱数不能大于999！",
          position: "bottom-right"
        });
        return;
      } else if (
        item.rule !== "U001" &&
        parseInt(item.endBoxNo) -
          parseInt(item.startBoxNo) +
          cartonNoList.length >
          3600
      ) {
        this.$notify.error({
          title: `箱号规则${item.rule}`,
          message: "总箱数不能大于3600！",
          position: "bottom-right"
        });
        return;
      } else if (parseInt(item.endBoxNo) - parseInt(item.startBoxNo) < 0) {
        this.$notify.error({
          title: "请正确填写开始和结束箱号",
          message: "起始箱号不能大于结束箱号！",
          position: "bottom-right"
        });
        return;
      } else if (item.startBoxNo) {
        this.showSelectDialog = true;
        // 当前选中 箱单
        this.showIndex = index;
        this.selectTable = clone(this.packingList[index].filterData);
        console.log("this.selectTable :>> ", this.selectTable);
      } else {
        this.$notify.error({
          title: "请填写开始和结束箱号",
          message: "起始箱号，结束箱号不能为空",
          position: "bottom-right"
        });
        return;
      }
      this.dialogHeadFn();
    },
    hideSelectDialog() {
      // console.log(
      //   '%chideSelectDialog: ',
      //   'color: MidnightBlue; background: Aquamarine;'
      // )
      this.showSelectDialog = false;
      this.dialogInfo = {
        length: "",
        width: "",
        height: "",
        grossWeight: ""
      };
      this.selectTable = [];
      this.packingList[this.showIndex].filterData.forEach(i => {
        i.inputNum = "0";
      });
      this.showRowIndex = "";
    },

    // 选择SKU
    async enterSelectSku() {
      /**
       * 1.获取表单现有得数据，相同箱号，SKU的数据进行数据修改；相同箱号不同SKU进行 合并
       */
      const obj = Object.assign({}, this.packingList[this.showIndex]);
      // console.log('obj :>> ', obj)
      // 获取箱数
      const startBoxNo = parseInt(obj.startBoxNo);
      const endBoxNo = parseInt(obj.endBoxNo ? obj.endBoxNo : obj.startBoxNo);
      const rowNum = 1 - (startBoxNo - endBoxNo);
      const arrayList = [];
      // 修改已填写箱数
      for (const i of this.selectTable) {
        if (!i.inputNum) {
          this.$message.error("请填写填装数量！");
          return;
        }
        if (parseInt(i.inputNum) === 0) {
          continue;
        }
        // 修改对应数据 packingNum
        const target = this.packingList[this.showIndex].filterData.find(
          x => x.skuName === i.skuName
        );
        target.packingNum =
          parseInt(i.inputNum * rowNum) +
          (i.packingNum ? parseInt(i.packingNum) : 0);

        // 生成的表格数据
        for (let index = 0; index < rowNum; index++) {
          if (parseInt(i.inputNum) !== 0) {
            // 获取箱号
            const boxNum = (startBoxNo + index).toString();
            const ruleStr =
              obj.rule.slice(0, obj.rule.length - boxNum.length) + boxNum;
            // 箱号
            const cartonNo = `${obj.shipmentId + ruleStr}`;
            const data = {
              shipmentId: obj.shipmentId,
              cartonNo: cartonNo,
              grossWeight: this.dialogInfo.grossWeight,
              length: this.dialogInfo.length,
              height: this.dialogInfo.height,
              width: this.dialogInfo.width,
              skuName: i.skuName,
              declareNameCn: i.declareNameCn,
              declareNameEn: i.declareNameEn,
              skuNum: i.inputNum
            };
            arrayList.push(data);
          }
        }

        i.inputNum = "0";
      }

      await this.checkData(arrayList);
    },
    // 编辑SKU
    editSelectSku() {
      const arr = [];

      for (const i of this.selectTable) {
        for (const j of this.selectTableData.data) {
          // 同数据，数量改变
          if (i.skuName === j.skuName) {
            j.shipmentId = this.packingList[this.showIndex].shipmentId;
            j.grossWeight = this.dialogInfo.grossWeight;
            j.length = this.dialogInfo.length;
            j.height = this.dialogInfo.height;
            j.width = this.dialogInfo.width;
            j.skuNum = i.inputNum;
            const target = this.packingList[this.showIndex].filterData.find(
              x => x.skuName === i.skuName
            );
            target.packingNum = i.inputNum + i.packingNum;
          }

          // 表格中不存在，新增的数据
          if (
            i.inputNum > 0 &&
            !this.selectTableData.nameArr.includes(i.skuName)
          ) {
            // console.log('表格中不存在，新增的数据 :>> ', obj)
            this.selectTableData.nameArr.push(i.skuName);
            i.packingNum = i.inputNum;

            const data = {
              cartonNo: j.cartonNo,
              grossWeight: this.dialogInfo.grossWeight,
              shipmentId: this.packingList[this.showIndex].shipmentId,
              length: this.dialogInfo.length,
              height: this.dialogInfo.height,
              width: this.dialogInfo.width,
              skuName: i.skuName,
              declareNameCn: i.declareNameCn,
              declareNameEn: i.declareNameEn,
              skuNum: i.inputNum
            };
            arr.push(data);
          }
        }
      }

      this.checkData(arr);
      this.dialogInfo = {
        length: "",
        width: "",
        height: "",
        grossWeight: ""
      };

      this.selectTable = [];
    },
    async checkData(arr) {
      if (arr.length === 0) {
        this.hideSelectDialog();
        return;
      }
      const d = clone(this.packingList[this.showIndex]);
      d.tableData = [...d.tableData, ...arr];
      // 合并相同箱号 同一sku 数据
      const combined = d.tableData.reduce((acc, cur) => {
        const target = acc.find(
          e => e.cartonNo === cur.cartonNo && e.skuName === cur.skuName
        );
        if (target) {
          // 存在相同，skunum相加
          target.skuNum += cur.skuNum;
        } else {
          acc.push(cur);
        }
        return acc;
      }, []);

      // console.log('combined :>> ', combined)
      this.packingList[this.showIndex].tableData = combined;
      this.$set(
        this.packingList,
        this.showIndex,
        await getSpanArr(this.packingList[this.showIndex])
      );
      // await getSpanArr(this.packingList[this.showIndex])

      this.hideSelectDialog();
    },
    async changeRule(val, item) {
      // item.rule
      // '当前箱号序号大于999,不能使用U001箱号规则,请重选箱号规则'
      const data = item.tableData;
      if (
        val === "U001" &&
        data.length > 0 &&
        data[data.length - 1].cartonNo.slice(3) > 999
      ) {
        this.$alert(
          "当前箱号序号大于999,不能使用U001箱号规则,请重选箱号规则",
          "U001箱号规则",
          {
            confirmButtonText: "确定",
            callback: action => {
              item.rule = item.oldRule;
            }
          }
        );
      } else {
        item.rule = val;
        item.oldRule = val;
        Object.assign(item, await changeCartonNo(item));
      }
    }
  }
};
</script>

<style scoped>
.el-select {
  width: calc(100% - 70px);
}
</style>

<style lang="scss" scoped>
.head-title {
  width: 70px;
}

.form-input-length {
  line-height: 36px;
}
</style>
